package com.withmiku.world.user.service.impl;

import com.withmiku.world.user.entity.User;
import com.withmiku.world.user.repository.UserRepository;
import com.withmiku.world.user.security.JwtUtils;
import com.withmiku.world.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service("userServiceImpl")
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;

    @Autowired
    public UserServiceImpl(BCryptPasswordEncoder passwordEncoder, JwtUtils jwtUtils, UserRepository userRepository) {
        this.passwordEncoder = passwordEncoder;
        this.jwtUtils = jwtUtils;
        this.userRepository = userRepository;
    }

    // 注册
    public User register(String username, String rowPassword, String email) {
        if (userRepository.findByUsername(username).isPresent()) {
            throw new RuntimeException("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(rowPassword));
        user.setEmail(email);
        user.setRole("USER");
        user.setStatus(1);

        return userRepository.save(user);
    }

    // 登录
    public String login(String username, String rowPassword) {
        User user = userRepository.findByUsername(username).
                orElseThrow(() -> new RuntimeException("用户名不存在"));
        if (!passwordEncoder.matches(rowPassword, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        return jwtUtils.generateToken(user.getUsername());
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    // 更新头像字段
    public void updateAvatar(String username, String avatarUrl) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setAvatar(avatarUrl);
        userRepository.save(user);
    }

    // 更新用户信息
    public void updateProfile(String username, User newInfo) {
        User user = userRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("用户不存在"));
        // 未来要修改更多信息可在此扩展
        if (newInfo.getUsername() != null) {
            user.setUsername(newInfo.getUsername());
        }
        if (newInfo.getEmail() != null) {
            user.setEmail(newInfo.getEmail());
        }
        userRepository.save(user);
    }

    @Override
    public User findById(Long userId) {
        return userRepository.findById(userId).orElseThrow(() -> new RuntimeException("用户不存在"));
    }
}
